<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/10/25
 * Time: 9:31
 */
namespace App\Http\Controllers\admin_system;

use App\Models\V1\DrpModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use SimpleSoftwareIO\QrCode\BaconQrCodeGenerator;
use App\Module\EntMemberInfo;
use App\Module\EntMemberDRP;
use App\Module\EntManageuser;
use App\Module\EntPushMoneyLog;
use Storage;
use Cookie;
use DB;
use Validator;
use Redirect;
use Session;
use Illuminate\Support\Facades\Input;

class MemberDRPController extends Controller
{
    protected $scaleOne = '0.3';
    protected $scaleTwo = '0.05';

    public function check_role($request){
        $manageUser = session('manageUser');
        $uri = $request->server('REQUEST_URI');
        //以下内容不能让普通游客进入
        $uris = [
            '/\/admin_system\/memberdrp\/indexAdd/',
            '/\/admin_system\/memberdrp\/indexAddTwo/',
            '/\/admin_system\/memberdrp\/index\/\d+\/edit/',
            '/\/admin_system\/memberdrp\/indexDelete/',
            '/\/admin_system\/member\/indexAdd/',
            '/\/admin_system\/member\/index\/\d+\/edit/',
            '/\/admin_system\/member\/indexDelete/',
        ];
         if($manageUser && $manageUser->role != 1){
             foreach($uris as $u){
                 if(preg_match($u,$uri)){
                     exit('<script>alert("权限不足!");history.back();</script>');
                 }
             }
         }
    }

    public function index(Request $request ,$keyword = '')
    {

        $memberdrp = DB::table('vw_memberdrp as a')
            ->leftJoin('memberdrp as b','b.DRPID','=','a.ParentID')
            ->leftJoin('memberinfo as d','d.MemNumber','=','b.MemNumber')
            ->select(
                'a.DRPID',
                'a.SalesMoney',
                'a.MemBalances',
                'a.FinishMoney',
                'a.UserID',
                'a.MemNumber',
                'a.UserName',
                'a.YourName',
                'a.States',
                'a.DeleteMark',
                'a.ReleaseDate',
                'a.AddDate',
                'd.YourName as parentName',
                'b.DRPID as parentDRPID')
            ->where('a.DeleteMark', '1')
            ->where('a.DRPLevel', '1')
            ->where('a.MemberDeleteMark',1);

        if($keyword){
            $memberdrp->where(function ($query) use ($keyword) {
                $query->orwhere('a.NickName', 'like', '%' . $keyword . '%')
                    ->orwhere('a.YourName', 'like', '%' . $keyword . '%')
                    ->orwhere('a.UserName', 'like', '%' . $keyword . '%');
            });
        }
        $memberdrp = $memberdrp->orderBy('a.ReleaseDate', 'desc')->paginate(20);
        return view('admin_system.memberdrp.index', [
            'memberdrp' => $memberdrp,
            'keyword' => $keyword
        ]);
    }


    public function createindex(Request $request)
    {
        $this->check_role($request);
        return view('admin_system.memberdrp.indexAdd');
    }

    public function createindexTwo(Request $request)
    {
        $this->check_role($request);
        return view('admin_system.memberdrp.indexAddTwo');
    }

    public function storeindex(Request $request)
    {
        $result = '';
        $AName = Session::get('AName');
        $AKey = Session::get('AKey');

        if ($AKey != '' && $AName != '') {
            $entManageuser = EntManageuser::select('UserID')->where('UserName', $AName)
                ->where('UserPwd', md5($AKey))
                ->where('DeleteMark', 1)
                ->first();
        }
        if ($entManageuser) {
            DB::beginTransaction();
            try {
                $memNumber = trim($request->get('hiNumber'));
                $salesMoney = trim($request->get('txtSalesMoney'));
                $entMemberDRPTwo = EntMemberDRP::select('DRPID', 'ParentID', 'FinishMoney', 'MemNumber')
                    ->where('MemNumber', $memNumber)
                    ->first();
                if ($entMemberDRPTwo) {
                    if ($entMemberDRPTwo->ParentID > 0) {

                        //返点30%
                        $entMemberDRPTree = EntMemberDRP::select('DRPID',
                            'ParentID',
                            'FinishMoney',
                            'SalesMoney',
                            'MemBalances',
                            'MemNumber',
                            'IsRebate')
                            ->where('DRPID', $entMemberDRPTwo->ParentID)
                            ->where('DeleteMark', 1)
                            ->first();
                        //验证是否满足销售指标
                        $money = 0;
                        $toalMoney = 0;
                        $memBalances = 0;
                        $finishMoney = $entMemberDRPTree->FinishMoney + $salesMoney;//当前指标加上合伙人已完成的销售指标
                        $k = 0;//判断调用提点算法
                        if ($finishMoney > $entMemberDRPTree->SalesMoney) {
                            //超过 计算返点，验证是否完成销售指标 记录销售指标

                            if ($entMemberDRPTree->FinishMoney < $entMemberDRPTree->SalesMoney) {
                                $k = 4;
                            } else {
                                $k = 2;
                            }
                        } else {
                            //未超过 不算返点，记录销售指标
                            if ($finishMoney == $entMemberDRPTree->SalesMoney) {
                                //未超过 不算返点，记录销售指标
                                $k = 1;
                            } else {
                                //超过 计算返点，验证是否完成销售指标 记录销售指标
                                $k = 3;
                            }
                        }
                        switch ($k) {
                            case 1:
                                $money = $finishMoney * $this->scaleOne;
                                $toalMoney = $finishMoney;
                                //完成销售指标返点
                                if ($entMemberDRPTree->IsRebate == 0) {
                                    $memBalances = $entMemberDRPTree->SalesMoney;
                                    DB::table('MemberDRP')
                                        ->where('DRPID', $entMemberDRPTree->DRPID)
                                        ->where('DeleteMark', 1)
                                        ->update(['IsRebate' => 1]);
                                }
                                break;
                            case 2:
                                $money = $salesMoney * $this->scaleOne;
                                $toalMoney = $salesMoney + $entMemberDRPTree->FinishMoney;
                                $memBalances = $money + $entMemberDRPTree->MemBalances;

                                //完成销售指标返点
                                if ($entMemberDRPTree->IsRebate == 0) {
                                    if ($toalMoney >= $entMemberDRPTree->SalesMoney) {
                                        $memBalances = $memBalances + $entMemberDRPTree->SalesMoney;
                                        DB::table('MemberDRP')
                                            ->where('DRPID', $entMemberDRPTree->DRPID)
                                            ->where('DeleteMark', 1)
                                            ->update(['IsRebate' => 1]);
                                    }
                                }
                                break;
                            case 3:
                                $toalMoney = $finishMoney;
                                $memBalances = $entMemberDRPTree->MemBalances;
                                break;
                            case 4:
                                $money = ($finishMoney - $entMemberDRPTree->SalesMoney) * $this->scaleOne;
                                $toalMoney = $salesMoney + $entMemberDRPTree->FinishMoney;
                                $memBalances = $money + $entMemberDRPTree->MemBalances;

                                //完成销售指标返点
                                if ($entMemberDRPTree->IsRebate == 0) {
                                    if ($toalMoney >= $entMemberDRPTree->SalesMoney) {
                                        $memBalances = $memBalances + $entMemberDRPTree->SalesMoney;
                                        DB::table('MemberDRP')
                                            ->where('DRPID', $entMemberDRPTree->DRPID)
                                            ->where('DeleteMark', 1)
                                            ->update(['IsRebate' => 1]);
                                    }
                                }
                                break;
                        }
                        DB::table('MemberDRP')
                            ->where('DRPID', $entMemberDRPTwo->ParentID)
                            ->where('DeleteMark', 1)
                            ->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances]);
                        DB::table('MemberDRP')
                            ->where('DRPID', $entMemberDRPTwo->DRPID)
                            ->where('DeleteMark', 1)
                            ->update(['DRPLevel' => '1', 'SalesMoney' => $salesMoney]);
                        $IsFinishTwo = 0;
                        if ($toalMoney > $entMemberDRPTree->SalesMoney) {
                            $IsFinishTwo = 1;
                        }
                        $entPushMoneyLog = new EntPushMoneyLog();
                        $entPushMoneyLog->MemNumber = $entMemberDRPTree->MemNumber;
                        $entPushMoneyLog->Scale = $this->scaleOne;
                        $entPushMoneyLog->TotalMoney = $toalMoney;
                        $entPushMoneyLog->PayMoney = $money;
                        $entPushMoneyLog->ToMemNumber = $memNumber;
                        $entPushMoneyLog->MemberType = 2;
                        $entPushMoneyLog->IsFinish = $IsFinishTwo;
                        $entPushMoneyLog->PushMoneyDesc = '发展合伙人提点30%';
                        $entPushMoneyLog->DeleteMark = 1;
                        $entPushMoneyLog->ReleaseDate = date('Y-m-d H:i:s', time());
                        $entPushMoneyLog->AddDate = date('Y-m-d H:i:s', time());
                        $entPushMoneyLog->save();
                        if (count($entMemberDRPTree) > 0) {
                            //返点5%
                            if ($entMemberDRPTree->ParentID > 0) {
                                $entMemberDRPFour = EntMemberDRP::select('DRPID', 'ParentID', 'FinishMoney', 'MemBalances', 'MemNumber')
                                    ->where('DRPID', $entMemberDRPTree->ParentID)
                                    ->where('DeleteMark', 1)
                                    ->first();

                                $moneyFour = $salesMoney * $this->scaleTwo;
                                $toalMoneyFour = $entMemberDRPFour->FinishMoney;
                                $memBalancesFour = $moneyFour + $entMemberDRPFour->MemBalances;
                                //是否完成指标
                                if ($entMemberDRPFour->IsRebate == 0) {
                                    if ($toalMoneyFour >= $entMemberDRPFour->SalesMoney) {
                                        $memBalancesFour = $memBalancesFour + $entMemberDRPFour->SalesMoney;
                                        DB::table('MemberDRP')
                                            ->where('DRPID', $entMemberDRPTree->DRPID)
                                            ->where('DeleteMark', 1)
                                            ->update(['IsRebate' => 1]);
                                    }
                                }

                                DB::table('MemberDRP')
                                    ->where('DRPID', $entMemberDRPTree->ParentID)
                                    ->where('DeleteMark', 1)
                                    ->update(['MemBalances' => $memBalancesFour]);
                                $IsFinish = 0;
                                if ($salesMoney >= $entMemberDRPFour->SalesMoney) {
                                    $IsFinish = 1;
                                }
                                $entPushMoneyLogTree = new EntPushMoneyLog();
                                $entPushMoneyLogTree->MemNumber = $entMemberDRPFour->MemNumber;
                                $entPushMoneyLogTree->Scale = $this->scaleTwo;
                                $entPushMoneyLogTree->TotalMoney = $salesMoney;
                                $entPushMoneyLogTree->PayMoney = $moneyFour;
                                $entPushMoneyLogTree->IsFinish = $IsFinish;
                                $entPushMoneyLogTree->MemberType = 2;
                                $entPushMoneyLogTree->ToMemNumber = $entMemberDRPTree->MemNumber;
                                $entPushMoneyLogTree->PushMoneyDesc = '下线合伙人发展合伙人提点5%';
                                $entPushMoneyLogTree->DeleteMark = 1;
                                $entPushMoneyLogTree->ReleaseDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLogTree->AddDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLogTree->save();
                            }
                        }
                        //生成二维码
                        //$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9cf54167b68b4c19&redirect_uri=http://wx.laohoulundao.com/music.html&response_type=code&scope=snsapi_base&state=' . $entMemberDRPTwo->DRPID . '#wechat_redirect';
                        $url = 'http://wx.laohoulundao.com/parent/' . $entMemberDRPTwo->DRPID . '.html';
                        $qrcode = new BaconQrCodeGenerator;
                        $qrcode->format('png')->size(300)->generate($url, public_path('/uploads/qrcode/' . $entMemberDRPTwo->MemNumber . '.png'));
                        if ($entPushMoneyLog) {
                            $result = '会员添加成功！';
                        } else {
                            $result = '会员添加失败！';
                        }
                    } else {
                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->where('DeleteMark', 1)->update(['DRPLevel' => '1', 'SalesMoney' => $salesMoney]);
                    }
                } else {

                    $entMemberDRP = new EntMemberDRP();
                    $entMemberDRP->MemNumber = $memNumber;
                    $entMemberDRP->SalesMoney = $salesMoney;
                    $entMemberDRP->MemBalances = 0;
                    $entMemberDRP->FinishMoney = 0;
                    $entMemberDRP->DRPScale = '0';
                    $entMemberDRP->DRPLevel = 1;
                    $entMemberDRP->IDTree = '';
                    $entMemberDRP->ParentID = 0;
                    $entMemberDRP->MasterID = $entManageuser->UserID;
                    $entMemberDRP->DeleteMark = 0;
                    $entMemberDRP->ReleaseDate = date('Y-m-d H:i:s', time());
                    $entMemberDRP->AddDate = date('Y-m-d H:i:s', time());
                    $entMemberDRP->IsRebate = 0;
                    $entMemberDRP->save();
                    //修改DOP状态
                    DB::table('MemberDRP')
                        ->where('DRPID', $entMemberDRP->DRPID)
                        ->update(['DeleteMark' => 1, 'IDTree' => '.' . $entMemberDRP->DRPID . '.']);
                    //生成二维码
                    // $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9cf54167b68b4c19&redirect_uri=http://wx.laohoulundao.com/music.html&response_type=code&scope=snsapi_base&state=' . $entMemberDRP->DRPID . '#wechat_redirect';
                    $url = 'http://wx.laohoulundao.com/parent/' . $entMemberDRP->DRPID . '.html';
                    $qrcode = new BaconQrCodeGenerator;
                    $qrcode->format('png')->size(300)
                        ->generate($url, public_path('/uploads/qrcode/' . $entMemberDRP->MemNumber . '.png'));
                    if ($entMemberDRP) {
                        $result = '会员添加成功！';
                    } else {
                        $result = '会员添加失败！';
                    }
                }

                DB::commit();
            } catch (Exception $e) {
                DB::rollBack();
            }

        } else {
            $result = '非法进入！';
        }
        return redirect::back()->withInput()->withErrors($result);
    }


    /**添加已有分销商没有提成
     * @param Request $request
     */
    public function storeindexTwo(Request $request)
    {
        $result = '';
        $AName = Session::get('AName');
        $AKey = Session::get('AKey');

        if ($AKey != '' && $AName != '') {
            $entManageuser = EntManageuser::select('UserID')->where('UserName', $AName)
                ->where('UserPwd', md5($AKey))
                ->where('DeleteMark', 1)
                ->first();
        }
        if ($entManageuser) {
            DB::beginTransaction();
            try {
                $userName = trim($request->get('txtUserName'));
                $entMemberInfo = EntMemberInfo::select('MemNumber')
                    ->where('UserName', $userName)
                    ->where('DeleteMark', '1')
                    ->first();
                //检查添加的用户是不是会员
                if ($entMemberInfo) {
                    $memberDRP = EntMemberDRP::select('DRPID', 'DRPLevel', 'MemNumber')
                        ->where('MemNumber', $entMemberInfo->MemNumber)
                        ->where('DeleteMark', '1')
                        ->first();

                    //如果该会员还不是合伙人
                    if (!$memberDRP) {
                        $entMemberDRP = new EntMemberDRP();
                        $entMemberDRP->MemNumber = $entMemberInfo->MemNumber;
                        $entMemberDRP->SalesMoney = 0;
                        $entMemberDRP->MemBalances = 0;
                        $entMemberDRP->FinishMoney = 0;
                        $entMemberDRP->DRPScale = '0';
                        $entMemberDRP->DRPLevel = 1;
                        $entMemberDRP->IDTree = '';
                        $entMemberDRP->ParentID = 0;
                        $entMemberDRP->MasterID = $entManageuser->UserID;
                        $entMemberDRP->DeleteMark = 0;
                        $entMemberDRP->ReleaseDate = date('Y-m-d H:i:s', time());
                        $entMemberDRP->AddDate = date('Y-m-d H:i:s', time());
                        $entMemberDRP->IsRebate = 1;
                        $entMemberDRP->save();

                        //修改DOP状态
                        DB::table('MemberDRP')
                            ->where('DRPID', $entMemberDRP->DRPID)
                            ->update(['DeleteMark' => 1, 'IDTree' => '.' . $entMemberDRP->DRPID . '.']);
                        //生成二维码
                        //$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9cf54167b68b4c19&redirect_uri=http://wx.laohoulundao.com/music.html&response_type=code&scope=snsapi_base&state=' . $entMemberDRP->DRPID . '#wechat_redirect';
                        $url = 'http://wx.laohoulundao.com/parent/' . $entMemberDRP->DRPID . '.html';
                        $imgpath = public_path('/uploads/qrcode/' . $entMemberDRP->MemNumber . '.png');
                        //删除已有的图片文件
                        if(file_exists($imgpath)){
                            unlink($imgpath);
                        }

                        $qrcode = new BaconQrCodeGenerator;
                        $qrcode->format('png')
                            ->size(300)
                            ->generate($url,$imgpath);
                        $result = '合伙人添加成功！';

                    } else {
                        //如果是扫描别人的二维码进来的，那么等级就为2,2代表合伙人吗，
                        if ($memberDRP->DRPLevel == 2) {
                            $entMemberDRP = EntMemberDRP::find($memberDRP->DRPID);
                            $entMemberDRP->DRPLevel = 1;
                            $entMemberDRP->MasterID = $entManageuser->UserID;
                            $entMemberDRP->DeleteMark = 1;
                            $entMemberDRP->ReleaseDate = date('Y-m-d H:i:s', time());
                            $entMemberDRP->AddDate = date('Y-m-d H:i:s', time());
                            $entMemberDRP->IsRebate = 1;
                            $entMemberDRP->save();
                            //生成二维码
                            //$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9cf54167b68b4c19&redirect_uri=http://wx.laohoulundao.com/music.html&response_type=code&scope=snsapi_base&state=' . $entMemberDRP->DRPID . '#wechat_redirect';
                            $url = 'http://wx.laohoulundao.com/parent/' . $entMemberDRP->DRPID . '.html';
                            $qrcode = new BaconQrCodeGenerator;
                            $qrcode->format('png')->size(300)->generate($url, public_path('/uploads/qrcode/' . $entMemberDRP->MemNumber . '.png'));
                            $result = '合伙人添加成功！';
                        } else {
                            $result = '您输入的账号已是合伙人，添加失败！';
                        }
                    }
                } else {
                    $result = '您输入的账号不是会员，合伙人添加失败！';
                }
                DB::commit();
            } catch (Exception $e) {
                DB::rollBack();
            }

        } else {
            $result = '合伙人添加失败！';
        }
        return redirect::back()->withInput()->withErrors($result);
    }


    /*
     * 合伙人详情信息
     *
     * */

    public function indexedit(Request $request, $id)
    {

        $this->check_role($request);
        $drpModel   = new DrpModel();
        //基本信息
        $memberdrp = DB::table('vw_memberdrp')
            ->select('DRPID', 'SalesMoney', 'UserName', 'YourName', 'MemNumber','ParentID')
            ->where('DRPID', $id)
            ->first();

        //下线会员
        $memberdrpTwo = DB::table('vw_memberdrp')
            ->select('DRPID', 'ParentID', 'UserName', 'DRPLevel', 'YourName', 'States', 'DeleteMark', 'ReleaseDate', 'AddDate')
            ->where('ParentID', $id)
            ->where('DeleteMark', 1)
            ->orderBy('ReleaseDate', 'desc')
            ->get();


        //提点记录
        $entPushMoneyLog = EntPushMoneyLog::select('PuMoID', 'TotalMoney', 'PayMoney', 'PushMoneyDesc', 'DeleteMark', 'ReleaseDate', 'AddDate')
            ->where('MemNumber', $memberdrp->MemNumber)
            ->where('DeleteMark', 1)
            ->orderBy('ReleaseDate', 'desc')
            ->get();



        //计算激活的会员和未激活的会员
        $vipMember   = 0;
        foreach($memberdrpTwo as $m){
            if($m->States == 1){
                $vipMember++;
            }
        }

        $parentDrpId    = $memberdrp->ParentID;

        if($parentDrpId > 0){
            $parentDrpInfo  = $drpModel->get_drp_info_by_drpid($parentDrpId);

            if($parentDrpInfo == false){
                exit("
                        <h2 style='text-align:center;'>本账户关系有异常,请告知后台维护人员</h2>
                        <div style='text-align:center;'><button onclick='history.back();' style='font-size:30px;padding:0px 10px;'>返回</button></div>
                        ");
            }

        }else{
            $parentDrpInfo = new \stdClass();
            $parentDrpInfo->YourName = "";
            $parentDrpInfo->DRPID = 0;

        }




        $memberNumber = ['total'=>count($memberdrpTwo),'vip'=>$vipMember];
        $data = [
            'entMemberDRP'      => $memberdrp,
            'memberdrpTwo'      => $memberdrpTwo,
            'entPushMoneyLog'   => $entPushMoneyLog,
            'member'            => $memberNumber,
            'parentDrpInfo'     => $parentDrpInfo
        ];
        return view('admin_system.memberdrp.indexEdit', $data);
    }




    public function AJAXDeleteSon(Request $request) {
        $DRPID = input::get('DRPID');

        EntMemberDRP::where('DRPID', $DRPID)->delete();

        $data['error'] = 0;
        return $data;
    }

    /**
     * 编辑
     *
     * */
    public function indexupdate(Request $request, $id)
    {
        $result = '';
        $AName = Session::get('AName');
        $AKey = Session::get('AKey');
        $parentUserId   = $request->input('parent_user_id');
        $entManageuser = EntManageuser::select('UserID')->where('UserName', $AName)
            ->where('UserPwd', md5($AKey))
            ->where('DeleteMark', 1)
            ->first();

        $entMemberDRP = EntMemberDRP::find($id);

        $drpModel   = new DrpModel();


        if($parentUserId > 0 ){ //更改学习官

            $parentDrpInfo        = $drpModel->get_member_drp_info($parentUserId);
            if(!$parentDrpInfo->DRPID){
                $result = "选择的父学习官还没有成为学习官";
                goto end;
            }

            $parentDrpId    = $parentDrpInfo->DRPID;
            $entMemberDRP->ParentID = $parentDrpId;
            $oldIdTree  = $entMemberDRP->IDTree;
            $newIdTree  = $parentDrpInfo->IDTree.$id.".";
            $entMemberDRP->IDTree   = $newIdTree;

            //所有的子学习官的IDTree还是以前的，需要改为最新的 使用替换的方式
            $sql = "UPDATE memberdrp
                      SET IDTree = REPLACE(IDTree,'{$oldIdTree}','{$newIdTree}')
                    WHERE IDTree like  '{$oldIdTree}%'";
            DB::update($sql);
        }elseif($parentUserId == -1){

            //把自己置顶为最上层的学习官
            $oldIdTree  = $entMemberDRP->IDTree;
            $newIdTree  = ".".$entMemberDRP->DRPID.".";
            $sql = "UPDATE memberdrp
                      SET IDTree = REPLACE(IDTree,'{$oldIdTree}','{$newIdTree}')
                    WHERE IDTree like  '{$oldIdTree}%'";
            DB::update($sql);
        }

        $entMemberDRP->SalesMoney = trim($request->get('txtSalesMoney'));
        $entMemberDRP->ReleaseDate = date('Y-m-d H:i:s', time());
        $entMemberDRP->MasterID = $entManageuser->UserID;
        $entMemberDRP->save();

       // $url = 'http://wx.laohoulundao.com/parent/' . $id . '.html';
       // $qrcode = new BaconQrCodeGenerator;
       // $qrcode->format('png')->size(300)->generate($url, public_path('/uploads/qrcode/' . $entMemberDRP->MemNumber . '.png'));

        $result = '会员修改成功！';
        end:
        return redirect::back()->withInput()->withErrors($result);
    }

    public function memberInfo(Request $request)
    {
        $result = '';
        try {
            if ($request->ajax()) {
                $KeyWords = $request->json('KeyWord');
                if ($KeyWords != '') {
                    $member = EntMemberInfo::select('UserID', 'UserName', 'NickName', 'YourName', 'MemNumber')
                        ->where('DeleteMark', '1')
                        ->where(function ($query) use ($KeyWords) {
                            $query->orwhere('NickName', 'like', '%' . $KeyWords . '%')
                                ->orwhere('YourName', 'like', '%' . $KeyWords . '%')
                                ->orwhere('UserName', 'like', '%' . $KeyWords . '%');
                        })
                        ->get();
                    $result = $member;
                } else {
                    $result = 'no';
                }
            } else {
                $result = 'no';
            }
        } catch (Exception $e) {
            $result = 'no';
        }
        return $result;
    }

    
    public function indexdelete(Request $request)
    { $this->check_role($request);
        $result = '';
        try {
            if ($request->ajax()) {
                $IDList = $request->json('IDList');
                if (is_numeric($IDList)) {
                    EntMemberDRP::where('DRPID', $IDList)->update([
                        'DeleteMark' => '0'
                    ]);
                    $result = 'ok';
                } else {
                    EntMemberDRP::whereIn('DRPID', explode(',', $IDList))->update([
                        'DeleteMark' => '0'
                    ]);
                    $result = 'ok';
                }
            }
        } catch (Exception $e) {
            $result = 'no';
        }
        return $result;
    }

    /**
     * 添加下线会员
     * @param Request $request
     * @return string
     */
    public function memberdrpvip(Request $request)
    {
        $result = '0';
        try {
            if ($request->ajax()) {
                $IDList = $request->json('IDList');
                $drpid = $request->json('drpid');

                if (is_numeric($drpid)) {
                    $AName = Session::get('AName');
                    $AKey = Session::get('AKey');

                    if ($AKey != '' && $AName != '') {
                        $entManageuser = EntManageuser::select('UserID')->where('UserName', $AName)
                            ->where('UserPwd', md5($AKey))
                            ->where('DeleteMark', 1)
                            ->first();
                    }
                    if ($entManageuser) {
                        $isMemberDRP = EntMemberDRP::select('DRPID', 'DRPLevel')->where('MemNumber', $IDList)->where('DeleteMark', '1')->first();
                        if (!$isMemberDRP) {
                            DB::beginTransaction();
                            try {
                                $entMemberDRP = new EntMemberDRP();
                                $entMemberDRP->MemNumber = $IDList;
                                $entMemberDRP->SalesMoney = 0;
                                $entMemberDRP->MemBalances = 0;
                                $entMemberDRP->FinishMoney = 0;
                                $entMemberDRP->DRPScale = '0';
                                $entMemberDRP->DRPLevel = 2;
                                $entMemberDRP->IDTree = '';
                                $entMemberDRP->ParentID = $drpid;
                                $entMemberDRP->MasterID = $entManageuser->UserID;
                                $entMemberDRP->DeleteMark = 0;
                                $entMemberDRP->ReleaseDate = date('Y-m-d H:i:s', time());
                                $entMemberDRP->AddDate = date('Y-m-d H:i:s', time());
                                $entMemberDRP->IsRebate = 1;
                                $entMemberDRP->save();
                                //修改DOP状态
                                DB::table('MemberDRP')->where('DRPID', $entMemberDRP->DRPID)->update(['DeleteMark' => 1, 'IDTree' => '.' . $drpid . '.' . $entMemberDRP->DRPID . '.']);
                                $result = '1';
                                DB::commit();
                            } catch (Exception $e) {
                                DB::rollBack();
                            }
                        } else {
                            if ($isMemberDRP->DRPLevel == 1) {
                                $entMemberDRP = EntMemberDRP::find($isMemberDRP->DRPID);
                                $entMemberDRP->ParentID = $drpid;
                                $entMemberDRP->IDTree = '.' . $drpid . '.' . $entMemberDRP->DRPID . '.';
                                $entMemberDRP->MasterID = $entManageuser->UserID;
                                $entMemberDRP->ReleaseDate = date('Y-m-d H:i:s', time());
                                $entMemberDRP->AddDate = date('Y-m-d H:i:s', time());
                                $entMemberDRP->save();
                                $result = '1';
                            } else {
                                if ($isMemberDRP->DRPLevel == 2) {
                                    $entMemberDRP = EntMemberDRP::find($isMemberDRP->DRPID);
                                    $entMemberDRP->ParentID = $drpid;
                                    $entMemberDRP->IDTree = '.' . $drpid . '.' . $entMemberDRP->DRPID . '.';
                                    $entMemberDRP->MasterID = $entManageuser->UserID;
                                    $entMemberDRP->ReleaseDate = date('Y-m-d H:i:s', time());
                                    $entMemberDRP->AddDate = date('Y-m-d H:i:s', time());
                                    $entMemberDRP->save();
                                    $result = '1';
                                } else {
                                    $result = '2';
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception $e) {
            $result = '3';
        }
        return $result;
    }
}